﻿namespace com.crownpack
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using com.crownpack.Extensions.DoubleExtensions;
    using com.crownpack.Extensions.StringExtensions;
    using com.crownpack.InitiativesDao;

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;

    using ReferenceFieldValue = CustomerFieldValue;

    using ReferenceObject = Customer;

    public class CustomerFieldFieldControl : BaseFieldControl
    {
        #region Fields

        protected Label lblLocation;
        protected Label uiFull;
        protected DropDownList uiLocation;

        const string BR = "<br />";
        const string PARENTCUSTOMERNOTFOUND = "Parent customer number not found. Please verify configuration.";

        InitiativesConfiguration _configuration;

        #endregion Fields

        #region Properties

        public override string DisplayTemplateName
        {
            get
            {
                return "CustomerFieldDisplayRenderingTemplate";
            }
            set
            {
                base.DisplayTemplateName = value;
            }
        }

        public ReferenceFieldValue InternalObj
        {
            get;
            set;
        }

        public override object Value
        {
            get
            {
                EnsureChildControls( );
                if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
                {
                    validate( );

                    //setOtherFieldValues( );

                    ReferenceObject o = ReferenceObject.Deserialize( uiLocation.SelectedValue );

                    SPFieldMultiColumnValue mcv = new SPFieldMultiColumnValue( 3 );
                    mcv[ 0 ] = o.ParentCustomerNo.HasValue ? o.ParentCustomerNo.Value.ToString( ) : string.Empty;
                    mcv[ 1 ] = o.LocationNo.HasValue ? o.LocationNo.Value.ToString( ) : string.Empty;
                    mcv[ 2 ] = o.LocationName.HtmlEncode( );

                    return mcv;
                }
                else
                    return base.Value;
            }
            set
            {
                EnsureChildControls( );
                if ( ItemFieldValue == null )
                    return;

                SPFieldMultiColumnValue mcv = ( SPFieldMultiColumnValue ) ItemFieldValue;
                InternalObj = new ReferenceFieldValue( mcv );

                if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
                {
                    int? index = null;
                    int i = 0;
                    foreach ( ListItem item in uiLocation.Items )
                    {
                        if ( !string.IsNullOrEmpty( item.Value ) )
                        {
                            ReferenceObject o = item.Value.HtmlDecode( ).DeserializeFromXml<ReferenceObject>( );
                            if ( o.ParentCustomerNo.HasValue && InternalObj.ParentCustomerNo.HasValue && o.ParentCustomerNo.Value == InternalObj.ParentCustomerNo.Value && o.LocationNo.HasValue && InternalObj.LocationNo.HasValue && o.LocationNo.Value == InternalObj.LocationNo.Value )
                            {
                                index = i;
                                break;
                            }
                        }
                        i++;
                    }
                    if ( index.HasValue )
                        uiLocation.SelectedIndex = index.Value;
                }
                else
                {
                    string s = InternalObj.GetHtmlFormat( );
                    if ( ControlMode == SPControlMode.Display )
                        uiFull.Text = s;
                }
                base.Value = value;
            }
        }

        protected override string DefaultTemplateName
        {
            get
            {
                if ( ControlMode == SPControlMode.Display )
                    return DisplayTemplateName;
                else
                    return "CustomerFieldDefaultRenderingTemplate";
            }
        }

        InitiativesConfiguration configuration
        {
            get
            {
                if ( _configuration == null )
                {
                    InitiativesConfigurationDao dao = new InitiativesConfigurationDao( );
                    _configuration = dao.GetByClientSite( SPContext.Current.Web.ParentWeb.Url );
                }
                return _configuration;
            }
        }

        bool IsRequired
        {
            get
            {
                return SPContext.Current.Fields.GetField( this.FieldName ).Required;
            }
        }

        #endregion Properties

        #region Methods

        protected override void CreateChildControls( )
        {
            base.CreateChildControls( );
            if ( ControlMode == SPControlMode.Display )
            {
                uiFull = ( Label ) TemplateContainer.FindControl( "uiFull" );
            }
            else if ( ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New )
            {
                uiLocation = ( DropDownList ) TemplateContainer.FindControl( "uiLocation" );
                lblLocation = ( Label ) TemplateContainer.FindControl( "lblLocation" );

                labelRequired( );
                uiLocation_LoadValues( );
            }
        }

        protected override void RenderFieldForDisplay( HtmlTextWriter output )
        {
            if ( ItemFieldValue == null )
            {
                output.Write( string.Empty );
                return;
            }
            SPFieldMultiColumnValue mcv = ( SPFieldMultiColumnValue ) ItemFieldValue;
            InternalObj = new ReferenceFieldValue( mcv );

            string s = InternalObj.GetHtmlFormat( );
            output.Write( s );
        }

        string getCackeKey( int parentCustomerNo )
        {
            return string.Format( "CPCustomer_{0}", parentCustomerNo );
        }

        void labelRequired( )
        {
        }

        void uiLocation_LoadValues( )
        {
            List<ReferenceObject> l = null;
            if ( uiLocation != null && configuration != null && configuration.ParentCustomerNo.HasValue )
            {
                // get parent customer no
                int parentCustomerNo = configuration.ParentCustomerNo.Value.ToInt32( );

                l = ( List<ReferenceObject> ) Page.Cache.Get( getCackeKey( parentCustomerNo ) );
                if ( l == null || l.Count == 0 )
                {
                    SPSecurity.RunWithElevatedPrivileges( delegate( )
                    {
                        CustomerDao dao = new CustomerDao( );
                        l = dao.GetByParentCustomerNo( parentCustomerNo, configuration.SourceList );
                        Page.Cache.Add( getCackeKey( parentCustomerNo ),
                            l,
                            null,
                            Cache.NoAbsoluteExpiration,
                            new TimeSpan( 0, 15, 0 ), // 15 minutes
                            CacheItemPriority.Normal,
                            new CacheItemRemovedCallback(
                                delegate( string k, object v, CacheItemRemovedReason reason )
                                {
                                } ) );
                    } );
                }
            }

            if ( l != null && l.Count > 0 )
            {
                lblLocation.Text = BR;
                uiLocation.Enabled = true;
                uiLocation.Items.Add( string.Empty );
                foreach ( ReferenceObject o in l )
                {
                    StringBuilder sb = new StringBuilder( );
                    sb.AppendFormat( "{0} ({1}) -", o.LocationName, o.LocationNo );
                    if ( !string.IsNullOrEmpty( o.Address1 ) && !string.IsNullOrEmpty( o.Address1.Trim( ) ) )
                        sb.AppendFormat( " {0},", o.Address1.Trim( ) );
                    if ( !string.IsNullOrEmpty( o.City ) && !string.IsNullOrEmpty( o.City.Trim( ) ) )
                        sb.AppendFormat( " {0},", o.City.Trim( ) );
                    if ( !string.IsNullOrEmpty( o.St ) && !string.IsNullOrEmpty( o.St.Trim( ) ) )
                        sb.AppendFormat( " {0},", o.St.Trim( ) );
                    if ( !string.IsNullOrEmpty( o.SalesrepName ) && !string.IsNullOrEmpty( o.SalesrepName.Trim( ) ) )
                        sb.AppendFormat( " SR:{0},", o.SalesrepName.Trim( ) );
                    if ( !string.IsNullOrEmpty( o.BranchManager ) && !string.IsNullOrEmpty( o.BranchManager.Trim( ) ) )
                        sb.AppendFormat( " BM:{0}", o.BranchManager.Trim( ) );
                    string s = sb.ToString( ).TrimEnd( ',' );
                    sb = null;
                    uiLocation.Items.Add( new ListItem( s, o.Serialize( ) ) );
                }
            }
            else
            {
                uiLocation.Enabled = false;
                lblLocation.Text = string.Format( "{0}<span class='ms-formvalidation' title='{1}' >{1}</span>{0}", BR, PARENTCUSTOMERNOTFOUND );
            }
        }

        void validate( )
        {
            if ( IsRequired )
            {
                bool ok = true;

                // validate
                if ( uiLocation.SelectedIndex <= 0 )
                    ok = false;

                if ( !ok )
                    //throw new SPFieldValidationException( "You must specify a value for all required fields." );
                    throw new SPFieldValidationException( "You must specify a value for this required field." );
            }
            else
            {
                if ( uiLocation.Items.Count <= 0 )
                    throw new SPFieldValidationException( PARENTCUSTOMERNOTFOUND );
            }
        }

        #endregion Methods
    }
}